package com.hsogoo.avatar.spring.springboot;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import com.hsogoo.avatar.AvatarServer;
import com.hsogoo.avatar.enums.Protocol;
import com.hsogoo.avatar.processor.DefaultAvatarProcessor;
import com.hsogoo.avatar.transport.netty.AvatarNettyAcceptor;
import com.hsogoo.avatar.utils.NetworkUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * spring boot 项目通过这个类来启动Avatar服务
 * Created by za-huangsaigang on 2018/10/17.
 */
@Slf4j
public class AvatarApplicationContextInitializer implements ApplicationContextInitializer {

    @Override
    public void initialize(ConfigurableApplicationContext context) {
        ConfigurableEnvironment environment = context.getEnvironment();
        int port = Integer.valueOf(environment.getProperty("avatar.server.port"));
        String host = NetworkUtil.getLocalIpString();
        log.info("avatar server starting... host=[{}], port=[{}]", host, port);
        SocketAddress address = new InetSocketAddress(host, port);
        AvatarNettyAcceptor acceptor = new AvatarNettyAcceptor(Protocol.AVATAR, address);
        acceptor.withProcessor(new DefaultAvatarProcessor());
        try {
            acceptor.start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
